package com.cc.service.impl;

import com.cc.entity.UserInfo;
import com.cc.mapper.UserInfoMapper;
import com.cc.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
//业务层 ===编程式事务
//@Component
public class UserInfoServiceImpl2 implements IUserInfoService {
       @Autowired(required=false)//required=false
        private UserInfoMapper userInfoMapper;
       @Autowired
       private  TransactionTemplate transactionTemplate;
       //内部类
     class ZzResult{
         boolean  flag = false;
     }
    public boolean zz(final int from, final int to, final int money) {
//        final boolean  flag = false;
        final ZzResult result = new ZzResult();
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                     zzOptional(from,to,money);
                   //事务自动提交
                     result.flag =true;
                     System.out.println("=======事务提交了=====");
                } catch (Exception ex) {
                    System.out.println("=======事务回滚了=====");
                    //事务回滚
                    status.setRollbackOnly();
                }
            }
        });
        return result.flag;
    }
    private void zzOptional(int from, int to, int money) throws Exception {
//        SqlSession  sqlSession  = SqlSessionUtils.openSession();
//        System.out.println("sqlSession===>"+sqlSession);
//        userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);
        // 一,==============旺财的钱减少300==============
        // 1.1查询旺财有多少钱
        UserInfo wc = userInfoMapper.selectByPrimaryKey(from);
        System.out.println(wc);
        // 1.2扣旺财有300
        int result = 0;
        if(wc!=null) {
            wc.setMoney(wc.getMoney() - money);
            result = userInfoMapper.updateByPrimaryKey(wc);
        }
        // ==============二,来福的钱增加300==============
        // 1.1查询旺财有多少钱
        UserInfo lf = userInfoMapper.selectByPrimaryKey(to);
        System.out.println(lf);
        // 1.2扣旺财有300
        int result2 = 0;
        if (lf != null) {
            lf.setMoney(lf.getMoney() + money);
            result2 = userInfoMapper.updateByPrimaryKey(lf);
        }
        // ==============最后的结果==============
        if (result > 0 && result2 > 0) {
            System.out.println("转账成功！！");
            //sqlSession.commit();//提交事务
        } else {
            //sqlSession.rollback();//回滚事务
            System.out.println("转账失败！！");
            throw new Exception();
        }
    }
}






















